<template>
  <el-dialog
    :visible.sync="visible"
    :title="title"
    width="400px"
    @open="openDialog"
    @close="closeDialog">
    <el-upload
      ref="upload"
      :limit="1"
      :http-request="submitFile"
      :before-upload="beforeUpload"
      action="upload"
      drag>
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
    </el-upload>
    <div style="margin-top: 20px;">还没有模板？<el-button type="text" @click="handleExport">立即下载</el-button></div>
  </el-dialog>
</template>

<script>
import { importCustomer } from '../../api/common'

export default {
  name: 'Upload',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '上传文件'
    },
    accept: {
      type: String,
      default: 'xlsx'
    }
  },
  data() {
    return {
      visible: this.dialogVisible
    }
  },
  watch: {
    dialogVisible() {
      this.visible = this.dialogVisible
    }
  },
  methods: {
    openDialog() {
      this.$refs.upload.clearFiles()
    },
    closeDialog() {
      this.$emit('close-dialog', false)
    },
    beforeUpload(file) {
      const acceptArray = this.accept.split(',')
      const prefix = file.name.split('.')[1]
      let isAccept = false
      acceptArray.forEach(acc => {
        if (acc === prefix) {
          isAccept = true
        }
      })
      if (!isAccept) {
        this.$message.error('不支持此类型文件')
        return false
      }
      // 其他限制这里写
      return true
    },
    submitFile(data) {
      const formData = new FormData()
      formData.append('file', data.file)
      importCustomer(formData).then(res => {
        let data = res.data
        let msg = '上传成功' + data.succRows.length + '条，上传失败' + data.failRows.length + '条'
        this.$message({
          message: 'msg',
          type: 'success'
        })
        this.$emit('close-dialog', true)
      })
    },
    handleExport() {
      window.location.href = 'http://oss.idouedu.com/%E5%AE%A2%E6%88%B7%E6%A8%A1%E6%9D%BF-%E7%88%B1%E8%B1%86%E4%BC%98%E6%95%99.xlsx'
    }
  }
}
</script>

<style scoped>

</style>
